﻿using BlueportCoffee.http;
using BlueportCoffee.model;
using BlueportCoffee.RobotModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Interop;

namespace BlueportCoffee.MilkTeaModel
{
    public class MilkTeaSocket
    {
        private static MilkTeaSocket instance;
        private MilkTeaSocket() { }

        public static MilkTeaSocket Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MilkTeaSocket();
                }
                return instance;
            }
        }
        public List<ClientMessage> clientLists = new List<ClientMessage>();
        public bool AllBol = true;
        public int status { get; set; } = 0;
        /// <summary>
        /// 创建客户端
        /// </summary>
        public Socket client;
        public void Connect()
        {
            try
            {
                // 创建客户端
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ///IP地址
                IPAddress ip = IPAddress.Parse(IPorPortInfo.Instance.MilkTeaIP);
                ///端口号
                IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(IPorPortInfo.Instance.MilkTeaPort));
                ///建立与服务器的远程连接
                client.Connect(endPoint);
                ///线程问题
                Thread thread = new Thread(ReciveMsg);
                thread.IsBackground = true;
                thread.Start(client);
                Thread thread1 = new Thread(MsgShowServer);
                thread1.IsBackground = true;
                thread1.Start();
                Thread thread2 = new Thread(MaterialsList);
                thread2.IsBackground = true;
                thread2.Start();
            }
            catch (Exception)
            {
                return;
            }
        }
        public void MaterialsList()
        {
            while (true)
            {
                try
                {
                    if (Instance.AllBol)
                    {
                        Materials coffeemake = new Materials();
                        Instance.SendMsg(JsonConvert.SerializeObject(coffeemake) + "###");
                    }
                }
                catch (Exception)
                {
                }
                Thread.Sleep(60000);
            }
        }
        /// <summary>
        /// 客户端发送消息，服务端接收到
        /// </summary>
        public void SendMsg(string str)
        {
            Console.WriteLine("发的协议包：" + str);
            byte[] arrMsg = Encoding.UTF8.GetBytes(str);
            client.Send(arrMsg);
        }
        /// <summary>
        /// 客户端接收到服务器发送的消息
        /// </summary>
        /// <param name="o">客户端</param>
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    ///定义客户端接收到的信息大小
                    byte[] arrList = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = client.Receive(arrList);
                    string msg = Encoding.UTF8.GetString(arrList, 0, length);
                    Console.WriteLine(msg);
                    var list = msg.Split('#');
                    if (list.Count() >= 4)
                    {
                        var ClientList = JsonConvert.DeserializeObject<ClientMessage>(list[0]);
                        if (ClientList != null)
                        {
                            clientLists.Add(ClientList);
                        }
                    }
                    //richTextBox1.AppendText(msg);
                    // listBox1.Items.Add(msg);
                }
                catch (Exception)
                {
                    ///关闭客户端
                    client.Close();
                }

            }
        }
        public bool Ismake = false;
        public bool Islock = false;
        public bool IsDev = false;
        public bool IsMater = false;
        public string materials = "";
        public void MsgShowServer()
        {

            try
            {
                while (true)
                {
                    try
                    {
                        if (clientLists.Count > 0)
                        {
                            var ClientList = clientLists[0];
                            if (ClientList != null)
                            {
                                if (ClientList.cmd == "devies")
                                {
                                    Instance.IsDev = true;
                                    var datas = JsonConvert.DeserializeObject<Datas>(ClientList.data.ToString());
                                    if (datas != null)
                                    {
                                        Instance.status = datas.status;
                                    }
                                }
                                else if (ClientList.cmd == "status" || ClientList.cmd == "make")
                                {
                                    Instance.Ismake = true;
                                }
                                else if (ClientList.cmd == "lock")
                                {
                                    Instance.Islock = true;
                                }
                                else if (ClientList.cmd == "materials")
                                {
                                    Instance.IsMater = true;
                                    materials = ClientList.data.ToString();
                                    Alter alter = new Alter();
                                    alter.equipNo = "10070";
                                    alter.equipAlterInfo = materials;
                                    alter.equipAlterType = "2";
                                    string lists = JsonConvert.SerializeObject(alter);
                                    HttpMsg.Instance.saveDeviceMatterMsg(lists);
                                }

                            }
                            clientLists.RemoveAt(0);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    Thread.Sleep(100);
                }
            }
            catch (Exception)
            {
                return;
            }
        }
    }
}
